<template>
  <div class="content-wrapper">
    <a-col :style="{ width: '280px' }">
      <div class="category-wrapper">
        <a-input-search ref="searchInput" v-model:value="store.searchText" placeholder="搜索书签... " class="search-input" @focus="handleFocusSearch" @blur="handleBlurSearch" />
        <CategoryList
          v-model="store.selectedCategory"
          :categories="store.categories"
          @add="showAddCategoryModal"
          @delete="handleCategoryDelete"
          @edit="handleCategoryEdit"
          @exportCategory="handleCategoryExport"
          @importCategory="handleCategoryImport"
          @sort="handleCategorySort"
        />
      </div>
    </a-col>

    <a-col :style="{ width: 'calc(100% - 240px)' }">
      <BookmarkList :bookmarks="store.filteredBookmarks" @add="showAddBookmarkModal" @edit="editBookmark" @delete="deleteBookmark" @sort="handleBookmarkSort" />
    </a-col>

    <AddBookmarkModal v-model:open="store.isBookmarkModalOpen" :categories="store.categories" :editing-bookmark="editingBookmark" @submit="handleBookmarkSubmit" />

    <AddCategoryModal v-model:open="store.isCategoryModalOpen" @submit="handleCategorySubmit" />
  </div>
</template>

<script setup>
import { useBookmarkStore } from '@/stores/bookmark'
import { useUserStore } from '@/stores/user'
import { ref, nextTick, onMounted, onUnmounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import CategoryList from '@/components/CategoryList/index.vue'
import BookmarkList from '@/components/BookmarkList/index.vue'
import AddBookmarkModal from '@/components/Modals/AddBookmarkModal.vue'
import AddCategoryModal from '@/components/Modals/AddCategoryModal.vue'

const store = useBookmarkStore()
const userStore = useUserStore()
const editingBookmark = ref(null)
const searchInput = ref(null)
const isSearchFocused = ref(false)
const loading = ref(false)

// 初始化数据
const initializeData = async () => {
  try {
    await store.initializeData()

    // 设置默认选中的分类
    nextTick(() => {
      // 默认选中"全部"分类，这样用户能看到所有书签
      store.selectedCategory = ['all']
    })
  } catch (error) {
    message.error('加载数据失败，请刷新页面重试')
  }
}

// 监听用户登录状态变化
watch(
  () => userStore.isAuthenticated,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      // 用户状态变化时重新初始化数据
      initializeData()
    }
  }
)

// 确保 store 数据已加载
onMounted(async () => {
  await initializeData()

  window.addEventListener('addBookmark', handleAddBookmark)
  window.addEventListener('focusSearch', handleFocusSearch)
})

onUnmounted(() => {
  window.removeEventListener('addBookmark', handleAddBookmark)
  window.removeEventListener('focusSearch', handleFocusSearch)
})

// 从 App.vue 复制相关方法
const showAddBookmarkModal = () => {
  editingBookmark.value = {
    title: '',
    url: '',
    description: '',
    categoryId: store.selectedCategory[0]
  }
  store.isBookmarkModalOpen = true
}

const showAddCategoryModal = () => {
  store.isCategoryModalOpen = true
}

const handleBookmarkSubmit = async (formData) => {
  if (!formData.title || !formData.url) {
    message.error('请填写完整信息')
    return
  }

  loading.value = true
  try {
    if (editingBookmark.value?.id) {
      await store.updateBookmark(editingBookmark.value.id, formData)
      message.success('书签更新成功')
    } else {
      await store.addBookmark(formData)
      message.success('书签添加成功')
    }

    store.isBookmarkModalOpen = false
    editingBookmark.value = null
    // 确保搜索聚焦状态重置
    store.isSearchFocused = false
  } catch (error) {
    message.error(error.message || '操作失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleCategorySubmit = async (name) => {
  if (!name) {
    message.error('请输入分类名称')
    return
  }

  loading.value = true
  try {
    await store.addCategory(name)
    store.isCategoryModalOpen = false
    // 确保搜索聚焦状态重置
    store.isSearchFocused = false
    message.success('分类添加成功')
  } catch (error) {
    message.error(error.message || '创建分类失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleCategoryDelete = async (category) => {
  loading.value = true
  try {
    await store.deleteCategory(category)
    message.success('分类删除成功')
  } catch (error) {
    message.error(error.message || '删除分类失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleCategoryEdit = async (category) => {
  loading.value = true
  try {
    await store.updateCategory(category)
    message.success('分类名称修改成功')
  } catch (error) {
    message.error(error.message || '修改失败，请重试')
  } finally {
    loading.value = false
  }
}

const editBookmark = (bookmark) => {
  // 需要转换数据格式以适配模态框
  // 在线模式：通过分类ID找到key；离线模式：直接使用categoryId
  let categoryKey
  if (userStore.isAuthenticated) {
    categoryKey = store.categories.find((c) => c.id === bookmark.categoryId)?.key
  } else {
    categoryKey = bookmark.categoryId
  }

  editingBookmark.value = {
    ...bookmark,
    categoryId: categoryKey || store.selectedCategory[0] || 'all'
  }
  store.isBookmarkModalOpen = true
}

const deleteBookmark = async (bookmark) => {
  loading.value = true
  try {
    await store.deleteBookmark(bookmark.id)
    message.success('书签删除成功')
  } catch (error) {
    message.error(error.message || '删除书签失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleCategoryExport = (category) => {
  // 需要根据分类的数据库ID来过滤书签
  const categoryBookmarks = store.bookmarks.filter((b) => {
    const categoryKey = store.categories.find((c) => c.id === b.categoryId)?.key
    return categoryKey === category.key
  })

  const data = {
    category,
    bookmarks: categoryBookmarks
  }
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `bookmarks-${category.label}-${new Date().toISOString().split('T')[0]}.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  message.success(`已导出 ${category.label} 分类的书签`)
}

const handleCategoryImport = async ({ category, file }) => {
  const reader = new FileReader()
  reader.onload = async (e) => {
    loading.value = true
    try {
      const data = JSON.parse(e.target.result)
      if (data.bookmarks) {
        // 逐个添加书签到指定分类
        for (const bookmark of data.bookmarks) {
          await store.addBookmark({
            ...bookmark,
            categoryId: category.key
          })
        }
        message.success(`成功导入到 ${category.label} 分类`)
      } else {
        message.error('文件格式不正确')
      }
    } catch (error) {
      message.error('导入失败，请检查文件格式')
    } finally {
      loading.value = false
    }
  }
  reader.readAsText(file)
}

const handleCategorySort = async (newCategories) => {
  try {
    await store.sortCategories(newCategories)
  } catch (error) {
    message.error('排序失败，请重试')
  }
}

const handleBookmarkSort = async (newBookmarks) => {
  try {
    await store.sortBookmarks(newBookmarks)
  } catch (error) {
    message.error('排序失败，请重试')
  }
}

// 添加书签的处理函数
const handleAddBookmark = () => {
  editingBookmark.value = {
    title: '',
    url: '',
    description: '',
    categoryId: store.selectedCategory[0] || ''
  }
  store.isBookmarkModalOpen = true
}

// 聚焦搜索框的处理函数
const handleFocusSearch = () => {
  if (searchInput.value) {
    searchInput.value.focus()
    store.isSearchFocused = true
  }
}

const handleBlurSearch = () => {
  store.isSearchFocused = false
}
</script>

<style scoped>
.content-wrapper {
  display: flex;
  height: 100%;
  padding: 8px;
  gap: 12px;
  box-sizing: border-box;
  background-color: #f5f7fa;
  position: relative;
}

:deep(.ant-col) {
  height: 100%;
}

.category-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
  height: 100%;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.bookmark-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-input {
  padding: 0 2px;
}

/* 加载状态样式 */
:deep(.ant-spin-container) {
  height: 100%;
}

:deep(.ant-spin-spinning) {
  position: relative;
}
</style>
